<template>
  <div class="mainbox">
    <div style="margin-left: 95%">
      <el-button size="large" round color="black" @click="dialogVisible = true">
        +
      </el-button>
    </div>

    <!-- 添加分类弹窗 -->
    <el-dialog v-model="dialogVisible" title="添加分类" width="30%">
      <el-form
        :model="categoryModel"
        :rules="rules"
        label-width="100px"
        style="padding-right: 30px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input
            v-model="categoryModel.name"
            minlength="1"
            maxlength="10"
          ></el-input>
        </el-form-item>
        <el-form-item label="分类Id" prop="categoryId">
          <el-input
            v-model="categoryModel.categoryId"
            minlength="1"
            maxlength="15"
          ></el-input>
        </el-form-item>
        <el-form-item label="分类描述" prop="description">
          <el-input
            v-model="categoryModel.description"
            minlength="1"
            maxlength="55"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addCategory"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加product弹窗 -->
    <el-dialog v-model="dialogVisible2" :title="title" width="40%">
      <el-form
        :model="productModel"
        :rules="rules"
        label-width="100px"
        style="padding-right: 30px"
      >
        <el-form-item label="ProductName" prop="name">
          <el-input
            v-model="productModel.name"
            minlength="1"
            maxlength="10"
          ></el-input>
        </el-form-item>
        <el-form-item label="ProductId" prop="categoryId">
          <el-input
            v-model="productModel.productId"
            minlength="1"
            maxlength="15"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="productModel.description"
            minlength="1"
            maxlength="55"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
            class="avatar-uploader"
            :auto-upload="true"
            :show-file-list="false"
            action="/api/images"
            name="file"
            :headers="{ Authorization: tokenStore.token }"
            :on-success="uploadSuccess"
          >
            <img
              v-if="productModel.img"
              :src="productModel.img"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible2 = false">取消</el-button>
          <el-button type="primary" @click="addProduct"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-tabs
      v-model="editableTabsValue"
      type="card"
      class="demo-tabs"
      closable
      @tab-remove="removeTab"
      @click="tabClick"
    >
      <el-tab-pane
        v-for="item in categories"
        :key="item.name"
        :label="item.name"
        :name="item.id"
      >
        {{ item.description }}
        <el-card class="page-container">
          <el-table :data="products" style="width: 100%">
            <el-table-column label="序号" width="100" type="index">
            </el-table-column>
            <el-table-column label="ProductName" prop="name"></el-table-column>
            <el-table-column
              label="ProductID"
              prop="productId"
            ></el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="{ row }">
                <el-button
                  type="primary"
                  @click="showItemList(row)"
                  :icon="Search"
                  circle
                ></el-button>
                <el-button
                  type="danger"
                  @click="delProduct(row)"
                  :icon="Delete"
                  circle
                />
              </template>
            </el-table-column>
            <template #empty>
              <el-empty description="没有数据" />
            </template>
          </el-table>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <button
      class="add"
      @click="
        dialogVisible2 = true;
        title = 'Add Product';
      "
    >
      +
    </button>

    <!--item抽屉-->
    <el-drawer v-model="drawer" title="Item List" size="60%">
      <div>
        <el-card class="page-container">
          <el-table :data="items" style="width: 100%">
            <el-table-column label="序号" width="100" type="index">
            </el-table-column>
            <el-table-column label="ItemID" prop="itemId"></el-table-column>
            <el-table-column
              label="ProductID"
              prop="productId"
            ></el-table-column>
            <el-table-column
              label="ListPrice"
              prop="listPrice"
            ></el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="{ row }">
                <el-button type="primary" :icon="Edit" circle></el-button>
                <el-button type="danger" @click="delItem(row)" :icon="Delete" circle />
              </template>
            </el-table-column>
            <template #empty>
              <el-empty description="没有数据" />
            </template>
          </el-table>
        </el-card>
      </div>

      <div>
        <el-button class="inneradd" color="blue" @click="innerDrawer = true"
          >+</el-button
        >
        <el-drawer
          v-model="innerDrawer"
          title="Edit Item"
          :append-to-body="true"
          :before-close="handleClose"
          size="50%"
        >
          <!-- 添加item表单 -->
          <el-form :model="itemModel" label-width="100px">
            <el-form-item label="商品id">
              <el-input
                v-model="itemModel.itemId"
                placeholder="请输入id"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品价格">
              <el-input
                v-model="itemModel.listPrice"
                placeholder="请输入价格"
              ></el-input>
            </el-form-item>
            <el-form-item label="unitCost">
              <el-input
                v-model="itemModel.unitCost"
                placeholder="请输入unitCost"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品库存">
              <el-input
                v-model="itemModel.listPrice"
                placeholder="请输入库存数量"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品属性1">
              <el-input
                v-model="itemModel.attribute1"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品属性2">
              <el-input
                v-model="itemModel.attribute2"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品属性3">
              <el-input
                v-model="itemModel.attribute3"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品属性4">
              <el-input
                v-model="itemModel.attribute4"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品属性5">
              <el-input
                v-model="itemModel.attribute5"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <el-form-item label="supplierId">
              <el-input
                v-model="itemModel.supplierId"
                placeholder="请输入supplierId"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addItem">发布</el-button>
              <el-button type="info" @click="innerDrawer=false">暂存</el-button>
            </el-form-item>
          </el-form>
        </el-drawer>
      </div>
    </el-drawer>
  </div>
</template>
  
<script lang="ts" setup>
import { ref } from "vue";
import { Edit, Delete, Search } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { QuillEditor } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
//相关接口
import {
  categoryListService,
  addCategoryService,
  delCategoryService,
  productsListService,
  addProductService,
  delProductService,
  itemListService,
  addItemService,
  delItemService,
  editItemService
} from "@/api/category.js";
import { RefSymbol } from "@vue/reactivity";
import { useTokenStore } from "@/stores/token.js";
const tokenStore = useTokenStore();

//图片上传成功的回调函数
const uploadSuccess = (result) => {
  productModel.value.img = result.message;
  console.log(result.message)
};

//弹窗标题控制
const title = ref("");
//弹窗测试
/*const handleClose = (done: () => void) => {
  ElMessageBox.confirm("Are you sure to close this dialog?")
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
};
*/

//控制添加分类弹窗
const dialogVisible = ref(false);
const dialogVisible2 = ref(false);
//添加分类数据模型
const categoryModel = ref({
  name: "",
  categoryId: "",
  description: "",
  id: 9999,
});
//product
const productModel = ref({
  id: 0,
  productId: "",
  categoryId: "",
  name: "",
  description: "",
  img:''
});

//item
const itemModel = ref({
  id: 0,
  itemId: "string",
  productId: "string",
  listPrice: "string",
  unitCost: "string",
  supplierId: 0,
  status: "string",
  attribute1: "string",
  attribute2: "string",
  attribute3: "string",
  attribute4: "string",
  attribute5: "string",
  quantity: 0,
});
//添加分类表单校验
const rules = {
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  categoryId: [{ required: true, message: "请输入ID", trigger: "blur" }],
  productyId: [{ required: true, message: "请输入ID", trigger: "blur" }],
  description: [{ required: false, message: "请输入描述", trigger: "blur" }],
};

//随机生成唯一大类id
const RandomNumber = () => {
  const currentTimestamp = Date.now(); // 获取当前时间戳
  const randomSeed = (currentTimestamp % (1000000 - 1000)) + 1000; // 生成随机数种子
  const randomNum = Math.floor(Math.random() * randomSeed); // 生成随机数
  return randomNum;
};

//添加分类
//标签渲染

const addCategory = async () => {
  categoryModel.value.id = RandomNumber();
  let result = await addCategoryService(categoryModel.value);
  const newTabName = ++tabIndex;
  editableTabsValue.value = newTabName.toString();
  console.log(editableTabsValue.value);
  ElMessage.success("添加成功");
  //刷新
  categoryList();
  dialogVisible.value = false;
};

//分类数据类型
const categories = ref([
  {
    id: "1",
    categoryId: "defalut1",
    name: "defalut2",
    description: "defalut2",
  },
  {
    id: "2",
    categoryId: "defalut2",
    name: "defalut2",
    description: "defalut2",
  },
]);

//标签页数据
const products = ref([
  {
    id: 0,
    productId: "k-23",
    categoryId: "string",
    name: "string",
    description: "string",
  },
  {
    id: 1,
    productId: "k-22",
    categoryId: "string",
    name: "string",
    description: "string",
  },
]);

//获取所有分类
let tabIndex = 0;
const categoryList = async() => {
  let result = await categoryListService();
  categories.value = result.data.data;
  console.log("tabList:"+categories.value);
  tabIndex = categories.value.length;
};

categoryList();
//标签页
const editableTabsValue = ref(categories.value[0].name);
console.log(editableTabsValue);

//删除分类
const delCategory = (targetName: number): Promise<boolean> => {
  return new Promise((resolve) => {
    // 弹出确认框
    ElMessageBox.confirm("确认删除当前分类?", "Warning", {
      confirmButtonText: "确认",
      cancelButtonText: "我再想想",
      type: "warning",
    })
      .then(async () => {
        let result = await delCategoryService(targetName);
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        resolve(true); // 操作成功，返回布尔值 true
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "删除已取消",
        });
        resolve(false); // 操作取消，返回布尔值 false
      });
  });
};

//标签删除
const removeTab = (targetName: string) => {
  console.log("removeTab");
  const tabs = categories.value;
  let activeName = editableTabsValue.value;
  console.log(activeName);
  if (activeName === targetName) {
    tabs.forEach((tab, index) => {
      console.log("找");
      if (tab.id === targetName) {
        console.log("找到了" + tab.name + tab.id);
        const id = Number(tab.id);
        const check = delCategory(id);
        if (check) {
          const nextTab = tabs[index + 1] || tabs[index - 1];
          if (nextTab) {
            activeName = nextTab.name;
          }
        } else {
          console.log("取消了");
          return;
        }
      }
    });
  }
  editableTabsValue.value = activeName;
  categories.value = tabs.filter((tab) => tab.name !== targetName);
  categoryList();
};

//对应标签页的products

//查
const productList = async (id) => {
  //categories.value[id].categoryId
  let result = await productsListService(id);
  products.value = result.data.data;
};

const tabClick = () => {
  let activeName = editableTabsValue.value;
  console.log(activeName);
  productList(activeName);
  //console.log(products.value[0])
};

//增加
const addProduct = async () => {
  //查找当前选中分类的ID
  const temp = categories.value;
  let target = editableTabsValue.value;
  let targetId = null;
  temp.forEach((category, index) => {
    if (target === category.id) {
      targetId = category.categoryId;
    }
  });
  productModel.value.categoryId = targetId;
  productModel.value.id = RandomNumber();
  let activeName = editableTabsValue.value;
  let dataObj = {
    id: 0,
    requestBody: {
      productId:productModel.value.productId ,
      categoryId: activeName,
      name: productModel.value.name,
      description: `<img src="${productModel.value.img}">${productModel.value.description}`
    }
  };
  dataObj.id = Number(activeName);
  let result = await addProductService(dataObj);
  ElMessage.success("添加成功");
  //刷新
  productList(activeName);
  dialogVisible2.value = false;
  productModel.value = {
    id: 0,
    productId: "",
    categoryId: "",
    name: "",
    description: "",
    img:''
  };
};

//删除product
const delProduct = (row) => {
  ElMessageBox.confirm("确认删除该Product吗?", "温馨提示", {
    confirmButtonText: "确认",
    cancelButtonText: "我再想想",
    type: "warning",
  })
    .then(async () => {
      //查找当前选中分类的ID
      const temp = categories.value;
      let target = editableTabsValue.value;
      let targetId = null;
      temp.forEach((category, index) => {
        console.log(category);
        if (target == category.id) {
          targetId = category.id;
          console.log(targetId);
        }
      });
      let DataObj = {
        id1: null,
        id2: null,
      };
      DataObj.id1 = targetId;
      DataObj.id2 = Number(row.productId);
      console.log(DataObj);
      let result = await delProductService(DataObj);
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      productList(targetId);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "删除已取消",
      });
    });
};

//item相关
//抽屉控制

const drawer = ref(false);
const innerDrawer = ref(false);

const handleClose = (done: () => void) => {
  ElMessageBox.confirm("You still have unsaved data, proceed?")
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
};
//items
//items
const items = ref([
  {
    id: 0,
    itemId: "string",
    productId: "string",
    listPrice: "string",
    unitCost: "string",
    supplierId: 0,
    status: "string",
    attribute1: "string",
    attribute2: "string",
    attribute3: "string",
    attribute4: "string",
    attribute5: "string",
    quantity: 0,
  },
]);

let proId='';

//获取items
const itemList = async (id) => {
  proId = id;
  let result = await itemListService(id);
  items.value = result.data.data;
  console.log(items.value);
};

const showItemList = (row) => {
  itemList(row.productyId);
  drawer.value = true;
};

const addItem=async()=>{
  let id = proId;
  itemModel.value.status = "1";
  let DataObj={
    id1:id,
    body:itemModel.value
  }
  let result =await addItemService(DataObj);
  ElMessage.success("添加成功");
  innerDrawer.value=false;
  itemList(id);
}

const delItem = (row)=>{

  ElMessageBox.confirm(
    '确认要删除当前item?',
    'Warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '我再想想',
      type: 'warning',
    }
  )
    .then(async() => {
      let DataObj = {
    id1:proId,
    id2:row.itemId
  }
  let result = await delItemService(DataObj);
  itemList(proId);
      ElMessage({
        type: 'success',
        message: '删除已完成',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除已取消',
      })
    })
}




</script>
  



<style lang="scss">
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
.demo-tabs {
  margin-top: -20px;
}

.topadd {
  position: absolute;
  top: 73px;
  right: 40px;
}

.page-container {
  min-height: 100%;
  box-sizing: border-box;
}

.add {
  position: absolute;
  float: left;
  top: 80%;
  right: 3%;
  border-radius: 50%;
  width: 60px;
  height: 60px;
  font-size: 50px;
  font-weight: 600;
}

.inneradd {
  position: absolute;
  float: left;
  top: 55px;
  right: 30px;
  font-weight: 900;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #060707;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>